package cn.nfwx.tv.helper;

import android.app.Activity;
import android.content.Context;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.chiclam.android.updater.Updater;
import com.chiclam.android.updater.UpdaterConfig;
import com.trello.rxlifecycle2.LifecycleTransformer;

import java.lang.ref.WeakReference;
import java.util.List;

import cn.nfwx.tv.BuildConfig;
import cn.nfwx.tv.R;
import cn.nfwx.tv.base.BaseActivity;
import cn.nfwx.tv.callback.ResponseListener;
import cn.nfwx.tv.callback.ResponseWithFailListener;
import cn.nfwx.tv.controller.MovementController;
import cn.nfwx.tv.db.AppDatabase;
import cn.nfwx.tv.db.TvAppointment;
import cn.nfwx.tv.manager.AppointmentManager;
import cn.nfwx.tv.manager.UpgradeManager;
import cn.nfwx.tv.manager.UserManager;
import cn.nfwx.tv.model.Result;
import cn.nfwx.tv.model.User;
import cn.nfwx.tv.model.Version;
import cn.nfwx.tv.util.SharePrefUtil;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by zhouzechao on 2017/12/13.
 */

public class AccountHelper {

    private static AccountHelper instance;

//    private List<TvAppointment> tvAppointments;

    private int stats;
    private int loginLocation;
    private String _ip;
    private String companyName;

    public static AccountHelper getInstance() {
        if (instance == null) {
            synchronized (AccountHelper.class) {
                if (instance == null) {
                    instance = new AccountHelper();
                }
            }
        }
        return instance;
    }

    public boolean isLogin(Context context) {
        if (context == null) {
            return false;
        }
        return !TextUtils.isEmpty(getToken(context));
    }

    public String getAccount(Context context) {
        return SharePrefUtil.getUid(context);
    }

    public String getAccessToken(Context context) {
        return SharePrefUtil.getAccessToken(context);
    }

    public String getUserName(Context context) {
        return SharePrefUtil.getUserName(context);
    }

    public void setLiveStats(int liveStats) {
        stats = liveStats;
    }

    public int getLiveStats() {
        return stats;
    }

    public int getLoginLocation() {
        return loginLocation;
    }

    public void setLoginLocation(int loginLocation) {
        this.loginLocation = loginLocation;
    }

    /**
     * 刷新数据库的预约数据
     *
     * @param context
     */
    public void refreshDaoAppoint(final Context context, LifecycleTransformer<Boolean> lifecycleTransformer, final ValueCallback<Boolean> callback) {
        if (AccountHelper.getInstance().isLogin(context)) {
            final WeakReference<ValueCallback<Boolean>> weakReference = new WeakReference<>(callback);
            Observable.create(new ObservableOnSubscribe<Boolean>() {
                @Override
                public void subscribe(final ObservableEmitter<Boolean> emitter) throws Exception {
                    AppointmentManager.requestAppointmentList(context, new ResponseListener<String>() {
                        @Override
                        public void onResponse(String requestTag, String response) {
                            Result<List<TvAppointment>> result = JSON.parseObject(response, new TypeReference<Result<List<TvAppointment>>>() {
                            }.getType());
                            if (Result.RESULT_SUCCESS.equals(result.getMessage())) {
//                        TvAppointmentDao dao = new TvAppointmentDao(context);
//                        dao.addList(result.getData());
                                TvAppointment[] tvAppointments = new TvAppointment[result.getData().size()];
                                result.getData().toArray(tvAppointments);
                                if (AppDatabase.getInstance(context).isOpen()) {
                                    AppDatabase.getInstance(context).appointDao().insert(tvAppointments);
                                }
                            }
                            emitter.onNext(true);
                            emitter.onComplete();

                        }

                        @Override
                        public void onError(String requestTag, Throwable t) {

                        }

                        @Override
                        public void onFinish() {

                        }
                    });
                }
            }).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .compose(lifecycleTransformer)
                    .subscribe(new Observer<Boolean>() {
                        @Override
                        public void onSubscribe(Disposable d) {

                        }

                        @Override
                        public void onNext(Boolean aBoolean) {
                            ValueCallback<Boolean> valueCallback = weakReference.get();
                            if (valueCallback != null) {
                                valueCallback.onReceiveValue(aBoolean);
                            }
                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        }
    }

    /**
     * 保存用户
     *
     * @param context
     * @param user
     */
    public void saveUser(Context context, User user) {
        SharePrefUtil.saveIjkUser(context, user);
    }

    /**
     * 获取用户
     *
     * @param context
     * @return
     */
    public User getUser(Context context) {
        return SharePrefUtil.getIjkUser(context);
    }

    /**
     * 获取uid
     *
     * @param context
     * @return
     */
    public int getUid(Context context) {
        if (getUser(context) != null) {
            return getUser(context).getUid();
        }
        return 0;
    }

    /**
     * 获取uid
     *
     * @param context
     * @return
     */
    public String getPhone(Context context) {
        if (getUser(context) != null) {
            return getUser(context).getMobile();
        }
        return "";
    }

    /**
     * 获取token
     *
     * @param context
     * @return
     */
    public String getToken(Context context) {
        if (getUser(context) != null) {
            if (TextUtils.isEmpty(getUser(context).getToken())) {
                return "";
            }
            return getUser(context).getToken();
        }
        return "";
    }

    /**
     * 获取昵称
     *
     * @param context
     * @return
     */
    public String getNick(Context context) {
        if (getUser(context) != null) {
            return getUser(context).getNick();
        }
        return "";
    }

    /**
     * 保存nick
     *
     * @param context
     * @param nickName
     */
    public void saveNick(Context context, String nickName) {
        if (getUser(context) != null) {
            User user = getUser(context);
            user.setNick(nickName);
            saveUser(context, user);
        }
    }

    /**
     * 获取昵称
     *
     * @param context
     * @return
     */
    public String getLogo(Context context) {
        if (getUser(context) != null) {
            return getUser(context).getLogo();
        }
        return "";
    }


    /**
     * 清除用户
     *
     * @param context
     */
    public void clearUser(Context context) {
        SharePrefUtil.clearIjkUser(context);
    }

    /**
     * 检查更新
     *
     * @param baseActivity
     */
    public void checkIjkUpdate(final BaseActivity baseActivity) {
        UpgradeManager.requestIjkUpdate(baseActivity, new ResponseWithFailListener<String>() {
            @Override
            public void onResponse(String requestTag, String response) {
                Result<List<Version>> result = JSON.parseObject(response, new TypeReference<Result<List<Version>>>() {
                }.getType());
                if (result.getMessage().equals(Result.RESULT_SUCCESS)) {
                    for (final Version version : result.getData()) {
                        if (version.getPlatform().equals("android")) {
                            final boolean isForce = version.isForce();
                            if (BuildConfig.VERSION_CODE < version.getVersioncode()) {
                                MovementController.getInstance().setAppUpdate(true);
                                MovementController.getInstance().dimissMent(baseActivity.getSupportFragmentManager());
                                DialogFragmentHelper.showConfirmDialog(baseActivity.getSupportFragmentManager(), "有新版本:v" + version.getVersion(), version.getDetail(), "确定", "取消", false, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        DialogFragmentHelper.closeConfirmDialog(baseActivity.getSupportFragmentManager());
                                        UpdaterConfig config = new UpdaterConfig.Builder(baseActivity)
                                                .setTitle(baseActivity.getResources().getString(R.string.app_name))
                                                .setDescription(baseActivity.getString(R.string.system_download_description))
                                                .setFileUrl(version.getUrl())
                                                .setIsShowDownloadUI(true)
                                                .setDownloadPath(baseActivity.getFilesDir().getAbsolutePath())
                                                .setFilename("nfwx_" + version.getVersion() + ".apk")
                                                .setCanMediaScanner(true)
                                                .build();
                                        Updater.get().showLog(false).download(config);
                                    }
                                }, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        DialogFragmentHelper.closeConfirmDialog(baseActivity.getSupportFragmentManager());
                                        if (isForce) {
                                            ActivityHelper.getInstance().exitApp();
                                        }
                                    }
                                });
                            } else {
                                MovementController.getInstance().setAppUpdate(false);
                            }
                            break;
                        }
                    }
                }
            }

            @Override
            public void onError(String requestTag, Throwable t) {

            }

            @Override
            public void onFinish() {

            }

            @Override
            public void onFail(String requestTag, String response) {

            }
        });
    }

    /**
     * 用户来电
     *
     * @param activity
     * @param valueCallback
     */
    public void inCall(Activity activity, final ValueCallback<Boolean> valueCallback) {
        TelephonyManager tpm = (TelephonyManager) activity
                .getSystemService(Context.TELEPHONY_SERVICE);
        if (tpm != null) {
            tpm.listen(new PhoneStateListener() {
                           @Override
                           public void onCallStateChanged(int state, String incomingNumber) {
                               switch (state) {
                                   case TelephonyManager.CALL_STATE_IDLE: //空闲
                                       break;
                                   case TelephonyManager.CALL_STATE_RINGING: //来电
                                       if (valueCallback != null) {
                                           valueCallback.onReceiveValue(true);
                                       }
                                       break;
                                   case TelephonyManager.CALL_STATE_OFFHOOK: //摘机（正在通话中）
                                       break;
                               }
                           }
                       },
                    PhoneStateListener.LISTEN_CALL_STATE);
        }
    }

    /**
     * 获取IP地址
     *
     * @param context
     */
    public void requestIp(Context context) {
        requestIp(context, null);
    }

    /**
     * 获取IP地址
     *
     * @param context
     * @param valueCallback
     */
    public void requestIp(Context context, final ValueCallback<String> valueCallback) {
        _ip = "";
        UserManager.requestIp(context, new ResponseWithFailListener<String>() {
            @Override
            public void onResponse(String requestTag, String response) {
                Result<String> result = JSON.parseObject(response, new TypeReference<Result<String>>() {
                }.getType());
                String ip = result.getData();
                _ip = ip;
                if (valueCallback != null) {
                    valueCallback.onReceiveValue(_ip);
                }
            }

            @Override
            public void onError(String requestTag, Throwable t) {
                _ip = "";
            }

            @Override
            public void onFinish() {

            }

            @Override
            public void onFail(String requestTag, String response) {

            }
        });
    }

    /**
     * 获取IP地址
     *
     * @return
     */
    public String getIp() {
        return _ip;
    }

    /**
     * 获取key
     *
     * @return
     */
    public String getKey() {
        return "c8aa26993ba850ba5da86eab41a84aab1babfcba";
    }

    public String getCompanyName() {
        return companyName;
    }

    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }
}
